<!-- 传统生成排班对话框组件 -->
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="currentStep === 1 ? '生成排班配置' : '排班生成预览'"
    width="900px"
    :destroy-on-close="true"
  >
    <!-- 步骤指示器 -->
    <div class="simple-steps">
      <div
        class="step"
        :class="{ active: currentStep === 1, completed: currentStep > 1 }"
      >
        <div class="step-number">1</div>
        <div class="step-label">配置参数</div>
      </div>
      <div class="step-connector"></div>
      <div
        class="step"
        :class="{ active: currentStep === 2, completed: currentStep > 2 }"
      >
        <div class="step-number">2</div>
        <div class="step-label">预览确认</div>
      </div>
    </div>

    <!-- 第一步：配置表单 -->
    <div v-show="currentStep === 1">
      <el-form
        :model="formData"
        label-width="120px"
        :rules="formRules"
        ref="formRef"
      >
        <el-form-item label="生成周期" prop="date_range">
          <el-date-picker
            v-model="formData.date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 100%"
            :disabled-date="disabledPastDates"
          />
        </el-form-item>

        <el-form-item label="生成范围">
          <el-checkbox-group v-model="formData.departments">
            <el-checkbox
              v-for="dept in departmentOptions"
              :key="dept.value"
              :label="dept.value"
            >
              {{ dept.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="人员类型" prop="staff_types">
          <el-checkbox-group
            v-model="formData.staff_types"
            @change="handleStaffTypeChange"
          >
            <el-checkbox
              v-for="type in staffTypeOptions"
              :key="type.value"
              :label="type.value"
            >
              {{ type.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 排班类型选择 -->
        <el-form-item label="排班类型" prop="schedule_types">
          <el-checkbox-group
            v-model="formData.schedule_types"
            :disabled="!formData.staff_types.length"
          >
            <el-checkbox
              v-for="type in availableScheduleTypes"
              :key="type.value"
              :label="type.value"
            >
              {{ type.label }}
            </el-checkbox>
          </el-checkbox-group>
          <div v-if="!formData.staff_types.length" class="el-form-item__error">
            请先选择人员类型
          </div>
          <div
            v-if="
              formData.staff_types.length && availableScheduleTypes.length === 0
            "
            class="el-form-item__error"
          >
            当前选择的人员类型没有可用的排班类型
          </div>
        </el-form-item>

        <el-form-item label="覆盖策略" prop="overwrite_strategy">
          <el-radio-group v-model="formData.overwrite_strategy">
            <el-radio label="skip">跳过已有排班</el-radio>
            <el-radio label="overwrite">覆盖已有排班</el-radio>
            <el-radio label="merge">合并（保留调整）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="排除节假日">
          <el-switch v-model="formData.exclude_holidays" />
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input
            v-model="formData.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入生成排班的备注信息"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 第二步：预览确认 -->
    <div v-show="currentStep === 2" class="preview-step">
      <div class="preview-header">
        <div class="preview-stats">
          <el-tag type="info">生成周期: {{ dateRangeDays }}天</el-tag>
          <el-tag type="success">排班记录: {{ previewData.length }}条</el-tag>
          <el-tag type="warning">涉及人员: {{ staffCount }}人</el-tag>
          <el-tag type="primary">排班类型: {{ scheduleTypeCount }}种</el-tag>
        </div>
      </div>

      <div class="preview-content">
        <el-table
          :data="previewData"
          height="350"
          border
          stripe
          v-loading="previewLoading"
          style="width: 100%"
          :default-sort="{ prop: 'schedule_date', order: 'ascending' }"
        >
          <el-table-column
            prop="schedule_date"
            label="日期"
            width="110"
            sortable
          >
            <template #default="{ row }">
              <div class="date-cell">
                <div class="date-main">
                  {{ formatDisplayDate(row.schedule_date) }}
                </div>
                <div class="date-week">{{ getWeekDay(row.schedule_date) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="staff_name" label="人员" width="90" />
          <el-table-column prop="staff_type" label="人员类型" width="90">
            <template #default="{ row }">
              <el-tag :type="getStaffTypeTagType(row.staff_type)" size="small">
                {{ getStaffTypeLabel(row.staff_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="department_name" label="科室" width="120" />
          <el-table-column prop="schedule_type" label="排班类型" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getScheduleTypeTagType(row.schedule_type)"
                size="small"
              >
                {{ getScheduleTypeLabel(row.schedule_type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="time_slot_code"
            label="班次"
            width="80"
            align="center"
          >
            <template #default="{ row }">
              <el-tag
                v-if="row.time_slot_code === 'off'"
                type="info"
                effect="plain"
                size="small"
                class="time-slot-tag"
              >
                休息
              </el-tag>
              <el-tag
                v-else
                :type="getTimeSlotTagType(row.time_slot_code)"
                effect="plain"
                size="small"
                class="time-slot-tag"
              >
                {{ formatTimeSlot(row.time_slot_code) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="time_range" label="时间段" width="120">
            <template #default="{ row }">
              <span v-if="row.time_slot_code === 'off'" class="rest-time"
                >--</span
              >
              <span v-else>{{ getTimeRange(row.time_slot_code) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="工作地点" min-width="120" />
          <el-table-column
            prop="max_patients"
            label="最大患者"
            width="85"
            align="center"
          >
            <template #default="{ row }">
              <span v-if="row.max_patients > 0" class="patient-count">
                {{ row.max_patients }}
              </span>
              <span v-else class="no-limit">-</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="70" align="center">
            <template #default="{ row }">
              <el-tag
                v-if="isHoliday(new Date(row.schedule_date))"
                type="danger"
                size="small"
              >
                节假日
              </el-tag>
              <el-tag v-else type="success" size="small"> 工作日 </el-tag>
            </template>
          </el-table-column>
        </el-table>

        <div
          v-if="previewData.length === 0 && !previewLoading"
          class="empty-preview"
        >
          <el-empty description="暂无排班数据" />
        </div>

        <!-- 排班分布统计 -->
        <div v-if="previewData.length > 0" class="schedule-distribution">
          <el-divider content-position="left">排班分布统计</el-divider>
          <div class="distribution-stats">
            <div
              class="distribution-item"
              v-for="(count, type) in scheduleDistribution"
              :key="type"
            >
              <span class="distribution-label"
                >{{ getScheduleTypeLabel(type) }}:</span
              >
              <span class="distribution-count">{{ count }} 次</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleCancel" v-show="currentStep === 1"
        >取消</el-button
      >
      <el-button @click="currentStep = 1" v-show="currentStep === 2"
        >上一步</el-button
      >
      <el-button
        type="primary"
        @click="handleNextStep"
        :loading="previewLoading"
        :disabled="!canGenerate && currentStep === 1"
      >
        {{ currentStep === 1 ? "生成预览" : "确认生成" }}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, defineProps, defineEmits } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  departmentOptions: {
    type: Array,
    default: () => [],
  },
  staffTypeOptions: {
    type: Array,
    default: () => [],
  },
  scheduleTypeOptions: {
    type: Array,
    default: () => [],
  },
  scheduleTemplates: {
    type: Array,
    default: () => [],
  },
  staffTypeScheduleMap: {
    type: Object,
    default: () => ({
      doctor: [
        "outpatient",
        "inpatient",
        "emergency",
        "surgery",
        "consultation",
        "examination",
      ],
      nurse: ["inpatient", "outpatient", "service"],
      pharmacist: ["pharmacy"],
      finance: ["billing", "registration", "office"],
      administrative: ["office"],
      manager: ["office"],
      logistics: ["service"],
    }),
  },
  timeSlotList: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "confirm", "cancel"]);

// ==================== 组件状态 ====================
const currentStep = ref(1);
const previewLoading = ref(false);
const formRef = ref(null);

// ==================== 表单数据 ====================
const formData = reactive({
  date_range: [],
  departments: [],
  staff_types: [],
  schedule_types: [],
  overwrite_strategy: "skip",
  exclude_holidays: true,
  notes: "",
});

// 预览数据
const previewData = ref([]);

// ==================== 表单验证规则 ====================
const formRules = {
  date_range: [
    { required: true, message: "请选择生成周期", trigger: "change" },
  ],
  staff_types: [
    { required: true, message: "请选择人员类型", trigger: "change" },
  ],
  schedule_types: [
    { required: true, message: "请选择排班类型", trigger: "change" },
  ],
};

// ==================== 计算属性 ====================
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

/**
 * 可用的排班类型（根据选中的人员类型过滤）
 */
const availableScheduleTypes = computed(() => {
  if (!formData.staff_types.length) {
    return [];
  }

  const allowedTypes = new Set();
  formData.staff_types.forEach((staffType) => {
    const types = props.staffTypeScheduleMap[staffType] || [];
    types.forEach((type) => allowedTypes.add(type));
  });

  return props.scheduleTypeOptions.filter((option) =>
    allowedTypes.has(option.value)
  );
});

/**
 * 是否可以生成排班
 */
const canGenerate = computed(() => {
  return (
    formData.staff_types.length > 0 &&
    formData.schedule_types.length > 0 &&
    formData.date_range.length === 2
  );
});

/**
 * 排班周期天数
 */
const dateRangeDays = computed(() => {
  if (formData.date_range.length !== 2) return 0;
  const start = new Date(formData.date_range[0]);
  const end = new Date(formData.date_range[1]);
  return Math.ceil((end - start) / (1000 * 60 * 60 * 24)) + 1;
});

/**
 * 涉及人员数量
 */
const staffCount = computed(() => {
  const staffSet = new Set();
  previewData.value.forEach((item) => {
    staffSet.add(item.staff_id);
  });
  return staffSet.size;
});

/**
 * 排班类型数量
 */
const scheduleTypeCount = computed(() => {
  const typeSet = new Set();
  previewData.value.forEach((item) => {
    typeSet.add(item.schedule_type);
  });
  return typeSet.size;
});

/**
 * 排班分布统计
 */
const scheduleDistribution = computed(() => {
  const distribution = {};
  previewData.value.forEach((item) => {
    const type = item.schedule_type;
    distribution[type] = (distribution[type] || 0) + 1;
  });
  return distribution;
});

/**
 * 班次代码映射
 */
const timeSlotMap = computed(() => {
  const map = {};
  if (props.timeSlotList && Array.isArray(props.timeSlotList)) {
    props.timeSlotList.forEach((slot) => {
      if (slot.slot_code && slot.slot_name) {
        // 格式化时间显示 (HH:MM:SS -> HH:MM)
        const startTime = formatTimeDisplay(slot.start_time);
        const endTime = formatTimeDisplay(slot.end_time);
        const timeRange =
          startTime && endTime ? `${startTime}-${endTime}` : "--";

        map[slot.slot_code] = {
          label: slot.slot_name,
          time: timeRange,
          type: getTimeSlotType(slot.slot_code),
          description: slot.description || "",
        };
      }
    });
  }

  return map;
});

// ==================== 班次格式化方法 ====================

/**
 * 格式化班次显示
 */
const formatTimeSlot = (timeSlotCode) => {
  return timeSlotMap.value[timeSlotCode]?.label || timeSlotCode;
};

/**
 * 格式化时间显示 (HH:MM:SS -> HH:MM)
 */
const formatTimeDisplay = (timeString) => {
  if (!timeString) return "";

  // 处理 HH:MM:SS 格式
  if (timeString.includes(":")) {
    const parts = timeString.split(":");
    if (parts.length >= 2) {
      return `${parts[0]}:${parts[1]}`;
    }
  }
  return timeString;
};

/**
 * 获取班次标签类型
 */
const getTimeSlotType = (slotCode) => {
  const typeMap = {
    morning: "success", // 早班 - 绿色
    afternoon: "warning", // 中班 - 黄色
    night: "danger", // 夜班 - 红色
    full_day: "primary", // 全天班 - 蓝色
    office: "info", // 行政班 - 青色
    flexible: "", // 弹性班 - 默认
    off: "info", // 休息 - 灰色
  };
  return typeMap[slotCode] || "";
};

/**
 * 获取班次时间段
 */
const getTimeRange = (timeSlotCode) => {
  return timeSlotMap.value[timeSlotCode]?.time || "-";
};

/**
 * 获取班次标签类型
 */
const getTimeSlotTagType = (timeSlotCode) => {
  return timeSlotMap.value[timeSlotCode]?.type || "";
};

// ==================== 其他工具方法 ====================

/**
 * 获取人员类型标签
 */
const getStaffTypeLabel = (staffType) => {
  const option = props.staffTypeOptions.find((opt) => opt.value === staffType);
  return option ? option.label : staffType;
};

/**
 * 获取排班类型标签
 */
const getScheduleTypeLabel = (scheduleType) => {
  const option = props.scheduleTypeOptions.find(
    (opt) => opt.value === scheduleType
  );
  return option ? option.label : scheduleType;
};

/**
 * 获取人员类型标签样式
 */
const getStaffTypeTagType = (staffType) => {
  const typeMap = {
    doctor: "danger",
    nurse: "success",
    pharmacist: "warning",
    finance: "",
    administrative: "info",
  };
  return typeMap[staffType] || "";
};

/**
 * 获取排班类型标签样式
 */
const getScheduleTypeTagType = (scheduleType) => {
  const typeMap = {
    outpatient: "danger",
    inpatient: "success",
    emergency: "danger",
    surgery: "warning",
    consultation: "info",
  };
  return typeMap[scheduleType] || "";
};

/**
 * 格式化显示日期
 */
const formatDisplayDate = (dateStr) => {
  const date = new Date(dateStr);
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${month}-${day}`;
};

/**
 * 获取星期几
 */
const getWeekDay = (dateStr) => {
  const date = new Date(dateStr);
  const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  return weekDays[date.getDay()];
};

/**
 * 处理人员类型变化
 */
const handleStaffTypeChange = (newStaffTypes) => {
  if (newStaffTypes.length === 0) {
    formData.schedule_types = [];
  } else {
    const currentTypes = [...formData.schedule_types];
    formData.schedule_types = currentTypes.filter((type) =>
      availableScheduleTypes.value.some((opt) => opt.value === type)
    );
  }
};

/**
 * 禁用过去的日期
 */
const disabledPastDates = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
};

/**
 * 判断是否为节假日
 */
const isHoliday = (date) => {
  const holidays = [
    "2025-01-01", // 元旦
    "2025-02-10",
    "2025-02-11",
    "2025-02-12", // 春节
    "2025-04-04",
    "2025-04-05",
    "2025-04-06", // 清明
    "2025-05-01",
    "2025-05-02",
    "2025-05-03", // 劳动节
    "2025-06-10", // 端午
    "2025-09-17", // 中秋
    "2025-10-01",
    "2025-10-02",
    "2025-10-03", // 国庆
  ];
  return holidays.includes(formatDate(date));
};

/**
 * 格式化日期为 YYYY-MM-DD
 */
const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

/**
 * 从模板数据中获取人员信息
 */
const getStaffInfoFromTemplate = (template) => {
  let staffName = "";
  let avatar = "";

  switch (template.staff_type) {
    case "doctor":
      staffName = template.doctor_staff_name;
      avatar = template.staff_avatar;
      break;
    case "nurse":
      staffName = template.nurse_staff_name;
      avatar = template.staff_avatar;
      break;
    case "pharmacist":
      staffName = template.pharmacist_staff_name;
      avatar = template.staff_avatar;
      break;
    case "finance":
      staffName = template.finance_staff_name;
      avatar = template.staff_avatar;
      break;
    default:
      staffName = "未知人员";
  }

  if (!staffName) {
    return null;
  }

  return {
    id: template.staff_id,
    name: staffName,
    staff_type: template.staff_type,
    department_id: template.department_id,
    department_name: template.department_name,
    professional_title: template.professional_title,
    avatar: avatar,
  };
};

/**
 * 根据模板创建排班实例
 */
const createScheduleInstanceFromTemplate = (
  date,
  template,
  staff,
  notes = ""
) => {
  const dateStr = formatDate(date);

  const instance = {
    instance_id: null,
    template_id: template.schedule_id,
    schedule_date: dateStr,
    staff_type_code: template.staff_type_code,
    staff_type: template.staff_type,
    staff_id: template.staff_id,
    staff_name: staff.name,
    department_id: template.department_id,
    department_name: template.department_name,
    professional_title: template.professional_title,
    time_slot_code: template.time_slot_code,
    schedule_type: template.schedule_type,
    location:
      template.location || getLocationByType(template.schedule_type, template),
    fee_item_id: template.fee_item_id || null,
    fee_item_name: template.fee_item_name || null,
    fee_amount: template.fee_amount || null,
    max_patients:
      template.max_patients ||
      getMaxPatientsByScheduleType(template.schedule_type),
    actual_patients: 0,
    pharmacy_location: template.pharmacy_location || null,
    service_type: template.service_type || null,
    window_number: template.window_number || null,
    service_scope: template.service_scope || null,
    status: 1,
    notes:
      notes ||
      template.notes ||
      getDefaultNotes(template.schedule_type, staff, template.time_slot_code),
    avatar: staff.avatar,
    create_time: new Date().toISOString(),
    update_time: new Date().toISOString(),
  };

  return instance;
};

/**
 * 根据排班类型获取最大患者数
 */
const getMaxPatientsByScheduleType = (scheduleType) => {
  const maxPatientsMap = {
    outpatient: 30,
    emergency: 20,
    surgery: 10,
    examination: 25,
    consultation: 15,
    inpatient: 0,
    pharmacy: 0,
    billing: 0,
    registration: 0,
    office: 0,
    service: 0,
  };
  return maxPatientsMap[scheduleType] || 30;
};

/**
 * 获取默认备注信息
 */
const getDefaultNotes = (scheduleType, staff, timeSlot) => {
  return `系统自动生成 - ${staff.name}的${scheduleType}排班 - ${timeSlot}班次`;
};

/**
 * 根据排班类型和科室信息获取工作地点
 */
const getLocationByType = (scheduleType, departmentInfo = null) => {
  const typeConfig = props.scheduleTypeOptions.find(
    (item) => item.value === scheduleType
  );
  if (!typeConfig) return "工作区域";

  const defaultLocation = typeConfig.default_location || "工作区域";

  if (departmentInfo && departmentInfo.department_name) {
    return `${departmentInfo.department_name}${defaultLocation}`;
  }
  return defaultLocation;
};

/**
 * 生成排班数据核心方法
 */
const generateScheduleData = async () => {
  try {
    const newInstances = [];

    if (!formData.date_range || formData.date_range.length !== 2) {
      throw new Error("请选择生成周期");
    }

    const [startDate, endDate] = formData.date_range;
    const start = new Date(startDate);
    const end = new Date(endDate);

    const selectedDepartments = formData.departments || [];
    const selectedStaffTypes = formData.staff_types || [];
    const selectedScheduleTypes = formData.schedule_types || [];

    if (selectedStaffTypes.length === 0 || selectedScheduleTypes.length === 0) {
      throw new Error("请选择人员类型和排班类型");
    }

    // 根据选中的条件过滤排班模板
    const filteredTemplates = props.scheduleTemplates.filter((template) => {
      if (!selectedStaffTypes.includes(template.staff_type)) return false;
      if (!selectedScheduleTypes.includes(template.schedule_type)) return false;
      if (
        selectedDepartments.length > 0 &&
        !selectedDepartments.includes(template.department_id)
      ) {
        return false;
      }
      return template.is_active === 1;
    });

    if (filteredTemplates.length === 0) {
      throw new Error("没有找到符合条件的排班模板");
    }

    console.log("符合条件的模板数量:", filteredTemplates.length);

    // 遍历每一天
    const currentDate = new Date(start);
    while (currentDate <= end) {
      // 排除节假日（如果设置）
      if (formData.exclude_holidays && isHoliday(currentDate)) {
        currentDate.setDate(currentDate.getDate() + 1);
        continue;
      }

      // 获取当前日期是星期几（0-6，0是周日）
      const dayOfWeek = currentDate.getDay();
      // 转换为1-7的格式（周一到周日）
      const weekDay = dayOfWeek === 0 ? 7 : dayOfWeek;

      // 为每个符合条件的模板生成排班
      filteredTemplates.forEach((template) => {
        // 检查模板是否适用于当前星期
        const templateWeekDays = template.week_days
          ? template.week_days.split(",").map((day) => parseInt(day.trim()))
          : [];
        if (
          templateWeekDays.length > 0 &&
          !templateWeekDays.includes(weekDay)
        ) {
          return; // 跳过不匹配的星期
        }

        // 根据模板获取人员信息
        const staff = getStaffInfoFromTemplate(template);

        if (!staff) {
          console.warn(
            `未找到人员信息: staff_id=${template.staff_id}, staff_type=${template.staff_type}`
          );
          return;
        }

        const instance = createScheduleInstanceFromTemplate(
          currentDate,
          template,
          staff,
          formData.notes
        );

        newInstances.push(instance);
      });

      currentDate.setDate(currentDate.getDate() + 1);
    }

    return newInstances;
  } catch (error) {
    console.error("生成排班数据失败:", error);
    throw error;
  }
};

/**
 * 处理下一步操作
 */
const handleNextStep = async () => {
  if (currentStep.value === 1) {
    // 第一步：生成预览
    if (!formRef.value) return;

    try {
      await formRef.value.validate();
      previewLoading.value = true;

      // 生成排班数据
      const newInstances = await generateScheduleData();
      console.log("生成的排班实例:", newInstances);

      previewData.value = newInstances;
      currentStep.value = 2;

      ElMessage.success(`成功生成 ${newInstances.length} 条排班记录`);
    } catch (error) {
      if (error.errors) {
        ElMessage.warning("请完善表单信息");
      } else {
        console.error("生成排班失败:", error);
        ElMessage.error(error.message || "生成排班失败");
      }
    } finally {
      previewLoading.value = false;
    }
  } else {
    // 第二步：确认提交
    try {
      // 将生成的实例数据传递给父组件
      emit("confirm", {
        instances: previewData.value,
        overwriteStrategy: formData.overwrite_strategy,
        notes: formData.notes,
      });

      // 关闭对话框
      dialogVisible.value = false;
      currentStep.value = 1;

      ElMessage.success("排班生成成功");
    } catch (error) {
      console.error("提交排班失败:", error);
      ElMessage.error(error.message || "提交排班失败");
    }
  }
};

/**
 * 取消操作
 */
const handleCancel = () => {
  dialogVisible.value = false;
  currentStep.value = 1;
  emit("cancel");
};

/**
 * 重置表单
 */
const resetForm = () => {
  formData.date_range = [
    new Date(),
    new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
  ];
  formData.departments = props.departmentOptions.map((dept) => dept.value);
  formData.staff_types = [];
  formData.schedule_types = [];
  formData.overwrite_strategy = "skip";
  formData.exclude_holidays = true;
  formData.notes = "";
  previewData.value = [];
  currentStep.value = 1;
};

// 监听visible变化，初始化表单
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      resetForm();
    }
  }
);

defineExpose({
  resetForm,
});
</script>

<style scoped lang="scss">
/* 简单步骤指示器 */
.simple-steps {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24px;

  .step {
    display: flex;
    flex-direction: column;
    align-items: center;

    .step-number {
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background: #e4e7ed;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      font-weight: 600;
    }

    .step-label {
      font-size: 12px;
      color: #c0c4cc;
      margin-top: 4px;
    }

    &.active {
      .step-number {
        background: var(--el-color-primary);
      }

      .step-label {
        color: var(--el-color-primary);
        font-weight: 500;
      }
    }

    &.completed {
      .step-number {
        background: var(--el-color-success);
      }

      .step-label {
        color: var(--el-text-color-primary);
      }
    }
  }

  .step-connector {
    width: 60px;
    height: 2px;
    background: #e4e7ed;
    margin: 0 16px;

    .step.completed + & {
      background: var(--el-color-success);
    }
  }
}

/* 预览步骤 */
.preview-step {
  .preview-header {
    margin-bottom: 16px;

    .preview-stats {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;

      .el-tag {
        border-radius: 12px;
      }
    }
  }

  .preview-content {
    .empty-preview {
      height: 200px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

/* 日期单元格 */
.date-cell {
  text-align: center;

  .date-main {
    font-weight: 500;
    color: var(--el-text-color-primary);
  }

  .date-week {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 2px;
  }
}

/* 班次标签 */
.time-slot-tag {
  font-weight: 500;
  min-width: 40px;
}

/* 患者数量 */
.patient-count {
  font-weight: 500;
  color: var(--el-color-primary);
}

.no-limit {
  color: var(--el-text-color-placeholder);
  font-style: italic;
}

/* 排班分布统计 */
.schedule-distribution {
  margin-top: 16px;

  .distribution-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 8px;

    .distribution-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px 8px;
      background: #f5f7fa;
      border-radius: 4px;

      .distribution-label {
        font-size: 13px;
        color: var(--el-text-color-regular);
      }

      .distribution-count {
        font-weight: 500;
        color: var(--el-color-primary);
      }
    }
  }
}

:deep(.el-form-item__error) {
  font-size: 12px;
  margin-top: 4px;
}
</style>